package pbc.gx.ekp.addressbook.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pbc.gx.ekp.addressbook.utils.SecurityUtils;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class TakeTimeAspect {



    /**
     * 带有@TakeTime注解的方法
     */
    @Pointcut("execution(* pbc.gx.ekp.addressbook.controller..*.*(..))")
    public void takeTime() {

    }

    @Around("takeTime()")
    public Object process(ProceedingJoinPoint point) throws Throwable {
        SecurityUtils.setStartTime(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes == null) {
            return point.proceed();
        }
        HttpServletRequest request = attributes.getRequest();

        Object returnValue = point.proceed();

        String queryString = request.getQueryString();
        queryString = StringUtils.isNotBlank(queryString) ? "?" + queryString : "";
        log.info("请求URL:" + request.getRequestURL() + queryString + ",方法:" + request.getMethod() + ",用时:" + (System.currentTimeMillis() - SecurityUtils.getStarTime()) + "ms");
        return returnValue;
    }
}
